
//提示信息对象
let msg;
//列对象
let cols;
let studentIdArray = new Array();
let studentNameArray = new Array();
let URL = 'society-for/getExams?Deid=' + $("#deid").val()+'&roleId='+$("#roleId").val();
let options = $("#roleId").val() == 2 ? '#admin' : '#currentTableBar';
layui.config({
    base: '../lay/dist/'
});
layui.use(['form', 'table', 'laydate', 'notice', 'element'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,

        laydate = layui.laydate,
        notice = layui.notice,
        element = layui.element;
//enterScore

    msg = layui.notice;
    /**
     * 表格主题渲染
     */
    element.render();
    table.render({
        elem: '#exam',
        url: URL,
        method: 'post',
        parseData: function (res) {
            return {
                "code": res.success == true ? 0 : 1,
                "count": res.total,
                "data": res.data

            }
        },
        toolbar: '#toolbarDemo',
        defaultToolbar: ['filter', 'exports', 'print', {
            title: '提示',
            layEvent: 'LAYTABLE_TIPS',
            icon: 'layui-icon-tips'
        }],
        cols: [
            [
                {type: 'checkbox', fixed: 'left'},
                {field: 'studentid', hide: true},
                {
                    field: 'xid', width: 80, title: '序号', sort: true, templet: function (d) {
                        return d.LAY_INDEX;
                    }
                },
                {field: 'id', width: 100, title: 'ID', sort: true, hide: true},
                {field: 'studentName', width: 100, title: '姓名'},
                {
                    field: 'classname', width: 100, title: '班级', templet: function (result) {
                        return result.grade.classname;
                    }
                },
                {
                    field: 'semesterName', width: 100, title: '阶段', templet: function (result) {
                        return result.grade.semesterName
                    }
                },
                {
                    field: 'dename', width: 100, title: '申请部门', templet: function (result) {
                        return result.departments.dename;
                    }
                },
                {field: 'usersuggest', width: 150, title: '对学社的看法'},
                {field: 'evaluation', width: 150, title: '自我评价'},
                {
                    field: 'updatetime', width: 120, title: '处理时间', templet: function (result) {
                        return layui.laytpl.toDateString(result.updatetime);
                    }
                },
                {
                    field: 'sendsate' ,title: '是否通知',width: 100,templet:function (result) {
                        if (result.sendsate==3){
                            return '<span style="background-color: #1497f3;color: #ffffff;padding: 3px;border-radius:3px;font-size:5px !important">'+'已通知'+'</span>'

                        }else {
                            return '<span style="background-color: coral;color: #ffffff;padding: 3px;border-radius:3px;font-size:5px !important">'+'未通知'+'</span>'

                        }
                    }
                },
                {
                    field: 'applyState', width: 150, title: '进度', align: 'center', templet: function (result) {

                        if (result.applystate==-1){
                            return '<span style="background-color: #da4f49;color: #ffffff;padding: 3px;border-radius:3px;font-size:5px !important">'+'失败'+'</span>'
                        }else {
                            return '<div style="margin-top: 10%" class="layui-progress">\n' +
                                '  <div class="layui-progress-bar layui-bg-orange" lay-percent="'+parseInt((result.applystate)*10+50)+'%"></div>\n' +
                                '</div>\n' +
                                ' '
                        }

                    }
                },


                {title: '操作', minWidth: 250, toolbar: options, align: "center", fixed: 'right'}


            ]
        ],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 15,
        page: true,
        skin: 'line'
        , done: function (res, currentCount) {
            //table渲染完成后渲染element进度条
            element.render()
        }
    });

    /**
     * 监听搜索操作
     */
    form.on('submit(data-search-btn)', function (data) {
        var result = data.field;
        console.log(result)
        //执行搜索重载
        table.reload('exam', {
            url: 'society-for/Scoresearch',
            method: 'post'
            , where: {
                deid: $("#deid").val(),
                studentName:result.studentName
            }
        }, 'data');
        notice.success("搜索执行成功！");

        return false;
    });


    form.on('submit(send)', function (data) {



        var result = data.field;

        if (result.message==null||result.message=="") {
            notice.error("发送内容不能为空！");
            return false;
        }
        notice.success("执行成功！");

        $("#part").removeAttr("style"); //ie,ff均支持
        $("#part").css('display','none');//隐藏

        /**
         * 可获取
         *  // console.log(result.message);
         // console.log(studentIdArray)
         // console.log(studentNameArray);
         // console.log("发送的内容" + $("#message").text());
         */


        $.ajax({
            traditional:true,
            type:"post",
            url:URL,
            data: {"studentId":studentIdArray,
                    "text":result.message},
            dataType:"json",
            success:function(result){
                if (result.success == true) {
                    notice.success("发送成功,共发送" + studentIdArray.length + "条信息！");
                    table.reload('exam', {
                        url: 'society-for/getExams',
                        method: 'post'
                    }, 'data');

                }else {
                    notice.error("发送失败！");
                }
            }
        })

        return false;
    });

    /**
     * toolbar监听事件
     */
    table.on('toolbar(currentTableFilter)', function (obj) {
        if (obj.event === 'selectAll') { //
            table.reload('teacher', {
                url: 'teacher/all',
                method: "post"
            })
            notice.success("查询成功！");
        } else if (obj.event === 'notice') {

            let checkStatus = table.checkStatus(obj.config.id);
            let data = checkStatus.data;
            console.log(data);
            for (let i = 0; i < data.length; i++) {
                studentIdArray[i] = data[i].studentid;
                studentNameArray[i] = data[i].studentName
            }
            if (studentIdArray.length == 0) {
                notice.error("请至少选中一名用户");
                return;
            }
            //mycar获取到被选中的对象通过发送考试通知，和时间通知
            console.log($("#message").text());
            var name = studentNameArray.toString();
            $("#message").attr("placeholder",
                "1.请输入具体时间地点\r" +
                "2.请不要发送骚扰信息\r" +
                "3.本次发送名单如下:\r"+
                name);
            verifyAddContainer_s("通知选中用户", null, null, $("#addEmail"), $("#part"));

        }


    });
    /**
     * 工具行监听(删除/编辑)
     * */
    table.on('tool(currentTableFilter)', function (obj) {
        let data = obj.data;
        cols = obj;


        if (obj.event === 'Full') {
            let index = layer.open({
                title: '用户资料',
                type: 2,
                shade: 0.2,
                scrollbar: false,
                shadeClose: true,
                area: ['75%', '98%'],
                content: 'society-for/information?id=' + data.id,
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
            return false;
        } else if (obj.event === 'delete') {
            // layer.confirm('是否要删除此条记录？', function (index) {
            //
            //     $.post("teacher/del", {id: obj.data.id, userId: obj.data.userid}, function (result) {
            //         if (result.success != true) {
            //             notice.warning("删除失败！");
            //         } else {
            //             notice.success("删除成功！");
            //             obj.del()
            //         }
            //     })
            //     layer.close(index);
            // }, function (index) {
            //     layer.close(index);
            // });

        }else  if (obj.event === 'enterScore'){
            let index = layer.open({
                title: '录入分数',
                type: 2,
                shade: 0.2,
                scrollbar: false,
                shadeClose: true,
                area: ['45%', '88%'],
                content: 'enterScore?id=' + data.id,
                end: function(){
                    table.reload('exam');
                }
            });
        }else  if (obj.event==='pass'){
            let index=  layer.msg('稍等一下', {
                icon: 16
                ,shade: 0.01,
                time : false,
            });
            $.ajaxSettings.async = true;
            $.post("society-for/pass",{id:obj.data.id,userId:obj.data.userId,deId:obj.data.deid,studentId:obj.data.studentid},function (result) {
                if (result.success == true) {
                    layer.close(index);
                    table.reload('exam');
                     notice.success("通过申请操作成功！");

                }
                })
        }else  if (obj.event==='NO'){
            console.log("进入拒绝")
            let index=  layer.msg('稍等一下', {
                icon: 16
                ,shade: 0.01,
                time : false,
            });
            $.ajaxSettings.async = true;
            $.post("society-for/no",{id:obj.data.id,studentId:obj.data.studentid},function (result) {
                if (result.success == true) {
                    layer.close(index);
                    table.reload('exam');
                    notice.success("拒绝操作成功！");

                }
            })
        }

    });
    /**
     * 时间戳的处理
     * @param d
     * @param format
     * @returns {string}
     */
    layui.laytpl.toDateString = function (d, format) {
        var date = new Date(d || new Date())
            , ymd = [
            this.digit(date.getFullYear(), 4)
            , this.digit(date.getMonth() + 1)
            , this.digit(date.getDate())
        ]
            , hms = [
            this.digit(date.getHours())
            , this.digit(date.getMinutes())
            , this.digit(date.getSeconds())
        ];

        format = format || 'yyyy-MM-dd';

        return format.replace(/yyyy/g, ymd[0])
            .replace(/MM/g, ymd[1])
            .replace(/dd/g, ymd[2])
            .replace(/hh/g, hms[0])
            .replace(/mm/g, hms[1])
            .replace(/ss/g, hms[2]);
    };
    /**
     * 数字前置补零
     * @param num
     * @param length
     * @param end
     * @returns {*}
     */
    layui.laytpl.digit = function (num, length, end) {
        var str = '';
        num = String(num);
        length = length || 2;
        for (var i = num.length; i < length; i++) {
            str += '0';
        }
        return num < Math.pow(10, length) ? str + (num | 0) : num;
    };



    /**
     * 设置提示信息属性
     * @type {{hideEasing: string, positionClass: string, hideDuration: string, debug: boolean, closeButton: boolean, extendedTimeOut: string, showEasing: string, onclick: null, showDuration: string, iconClass: string, timeOut: string}}
     */
    notice.options = {
        closeButton: true,//显示关闭按钮
        debug: false,//启用debug
        positionClass: "toast-bottom-right",//弹出的位置,
        showDuration: "300",//显示的时间
        hideDuration: "1000",//消失的时间
        timeOut: "2000",//停留的时间
        extendedTimeOut: "1000",//控制时间
        showEasing: "swing",//显示时的动画缓冲方式
        hideEasing: "linear",//消失时的动画缓冲方式
        iconClass: 'toast-info', // 自定义图标，有内置，如不需要则传空 支持layui内置图标/自定义iconfont类名
        onclick: null, // 点击关闭回调
    };

    // notice.warning("");信息状态
    // notice.info("");
    // notice.error("");
    // notice.success("");

});
function parentPage(result, childData) {
    if (result.success == true) {
        cols.update({
            applyState:childData.applyState,
        })

        msg.info("修改成功");
        return;
    }
    msg.warning("修改失败")
}

